package com.isoft.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.isoft.entity.AirportInfo;
import com.isoft.entity.FlightDynamic;
import com.isoft.entity.GateAssignment;
import com.isoft.entity.MsgMeta;
import com.isoft.mapper.*;
import com.isoft.result.R;
import com.isoft.service.XmlImportService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 测试控制器
 * 提供系统功能测试和数据查询接口
 */
@RestController
@RequestMapping("/api/test")
@CrossOrigin(origins = "*")
public class TestController {

    private static final Logger logger = LoggerFactory.getLogger(TestController.class);

    @Autowired
    private XmlImportService xmlImportService;

    @Autowired
    private MsgMetaMapper msgMetaMapper;

    @Autowired
    private AirportInfoMapper airportInfoMapper;

    @Autowired
    private FlightDynamicMapper flightDynamicMapper;

    @Autowired
    private GateAssignmentMapper gateAssignmentMapper;

    @Autowired
    private StandAssignmentMapper standAssignmentMapper;

    @Autowired
    private BeltAssignmentMapper beltAssignmentMapper;

    /**
     * 系统状态检查
     * GET /api/test/status
     */
    @GetMapping("/status")
    public R getSystemStatus() {
        logger.info("检查系统状态");

        try {
            Map<String, Object> status = new HashMap<>();
            status.put("system", "运行正常");
            status.put("database", "MySQL连接正常");
            status.put("timestamp", System.currentTimeMillis());

            return R.ok(status);
        } catch (Exception e) {
            logger.error("系统状态检查失败", e);
            return R.error("系统状态异常: " + e.getMessage());
        }
    }

    /**
     * 测试本地XML导入功能
     * POST /api/test/import-local-xml
     */
    @PostMapping("/import-local-xml")
    public R testImportLocalXml() {
        logger.info("测试本地XML导入功能");

        try {
            XmlImportService.ImportResult result = xmlImportService.importAllXmlFiles();
            return R.ok(result);
        } catch (Exception e) {
            logger.error("测试XML导入失败", e);
            return R.error("导入测试失败: " + e.getMessage());
        }
    }

    /**
     * 查询消息元数据
     * GET /api/test/msg-meta
     */
    @GetMapping("/msg-meta")
    public R getMsgMeta(@RequestParam(defaultValue = "10") Integer limit) {
        logger.info("查询消息元数据，限制条数: {}", limit);

        try {
            List<MsgMeta> msgMetas = msgMetaMapper.selectList(null);

            // 限制返回条数
            if (msgMetas.size() > limit) {
                msgMetas = msgMetas.subList(0, limit);
            }

            Map<String, Object> result = new HashMap<>();
            result.put("total", msgMetaMapper.selectCount(null));
            result.put("data", msgMetas);
            result.put("limit", limit);

            return R.ok(result);
        } catch (Exception e) {
            logger.error("查询消息元数据失败", e);
            return R.error("查询失败: " + e.getMessage());
        }
    }

    /**
     * 查询机场信息
     * GET /api/test/airport-info
     */
    @GetMapping("/airport-info")
    public R getAirportInfo(@RequestParam(defaultValue = "10") Integer limit) {
        logger.info("查询机场信息，限制条数: {}", limit);

        try {
            List<AirportInfo> airportInfos = airportInfoMapper.selectList(null);

            // 限制返回条数
            if (airportInfos.size() > limit) {
                airportInfos = airportInfos.subList(0, limit);
            }

            Map<String, Object> result = new HashMap<>();
            result.put("total", airportInfoMapper.selectCount(null));
            result.put("data", airportInfos);
            result.put("limit", limit);

            return R.ok(result);
        } catch (Exception e) {
            logger.error("查询机场信息失败", e);
            return R.error("查询失败: " + e.getMessage());
        }
    }

    /**
     * 查询航班动态信息
     * GET /api/test/flight-dynamic
     */
    @GetMapping("/flight-dynamic")
    public R getFlightDynamic(
            @RequestParam(defaultValue = "1") Integer pageNo,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String ffid,
            @RequestParam(required = false) String flid) {
        logger.info("查询航班动态信息，页码: {}, 每页条数: {}, 航班标识: {}, 航班ID: {}", pageNo, pageSize, ffid, flid);

        try {
            // 构建查询条件
            QueryWrapper<FlightDynamic> queryWrapper = new QueryWrapper<>();
            if (ffid != null && !ffid.isEmpty()) {
                queryWrapper.like("ffid", ffid);
            }
            if (flid != null && !flid.isEmpty()) {
                queryWrapper.eq("flid", flid);
            }
            // 分页查询
            Page<FlightDynamic> page = new Page<>(pageNo, pageSize);
            IPage<FlightDynamic> pageResult = flightDynamicMapper.selectPage(page, queryWrapper);
            return R.ok(pageResult);
        } catch (Exception e) {
            logger.error("查询航班动态信息失败", e);
            return R.error("查询失败: " + e.getMessage());
        }
    }

    /**
     * 查询登机门分配信息
     * GET /api/test/gate-assignment
     */
    @GetMapping("/gate-assignment")
    public R getGateAssignment(@RequestParam(defaultValue = "10") Integer limit) {
        logger.info("查询登机门分配信息，限制条数: {}", limit);

        try {
            List<GateAssignment> gateAssignments = gateAssignmentMapper.selectList(null);

            // 限制返回条数
            if (gateAssignments.size() > limit) {
                gateAssignments = gateAssignments.subList(0, limit);
            }

            Map<String, Object> result = new HashMap<>();
            result.put("total", gateAssignmentMapper.selectCount(null));
            result.put("data", gateAssignments);
            result.put("limit", limit);

            return R.ok(result);
        } catch (Exception e) {
            logger.error("查询登机门分配信息失败", e);
            return R.error("查询失败: " + e.getMessage());
        }
    }

    /**
     * 获取数据统计信息
     * GET /api/test/data-stats
     */
    @GetMapping("/data-stats")
    public R getDataStats() {
        logger.info("获取数据统计信息");

        try {
            Map<String, Object> stats = new HashMap<>();

            stats.put("msgMetaCount", msgMetaMapper.selectCount(null));
            stats.put("airportInfoCount", airportInfoMapper.selectCount(null));
            stats.put("flightDynamicCount", flightDynamicMapper.selectCount(null));
            stats.put("gateAssignmentCount", gateAssignmentMapper.selectCount(null));
            stats.put("standAssignmentCount", standAssignmentMapper.selectCount(null));
            stats.put("beltAssignmentCount", beltAssignmentMapper.selectCount(null));

            // 获取可用的消息类型
            List<String> messageTypes = xmlImportService.getAvailableMessageTypes();
            stats.put("availableMessageTypes", messageTypes);

            return R.ok(stats);
        } catch (Exception e) {
            logger.error("获取数据统计信息失败", e);
            return R.error("获取统计失败: " + e.getMessage());
        }
    }

    /**
     * 清空测试数据
     * DELETE /api/test/clear-test-data
     */
    @DeleteMapping("/clear-test-data")
    public R clearTestData() {
        logger.info("清空测试数据");

        try {
            xmlImportService.clearAllImportedData();
            return R.ok("测试数据清空成功");
        } catch (Exception e) {
            logger.error("清空测试数据失败", e);
            return R.error("清空失败: " + e.getMessage());
        }
    }

    /**
     * 数据库连接测试
     * GET /api/test/db-connection
     */
    @GetMapping("/db-connection")
    public R testDatabaseConnection() {
        logger.info("测试数据库连接");

        try {
            // 尝试执行一个简单的查询来测试连接
            Long count = msgMetaMapper.selectCount(null);

            Map<String, Object> result = new HashMap<>();
            result.put("status", "连接正常");
            result.put("msgMetaTableCount", count);
            result.put("testTime", System.currentTimeMillis());

            return R.ok(result);
        } catch (Exception e) {
            logger.error("数据库连接测试失败", e);
            return R.error("数据库连接异常: " + e.getMessage());
        }
    }
} 